<?php
namespace control;
/*
*工资条类
*/

class paySlipClass extends adIndexClass
{
    private const title = '工资条';
    private const page = 'paySlip';
    private const table = 'work_sign_record';

    /*列表页-查询条件*/
    public function salaryRecordOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    L('salary.table.yue_fen') => text(array("name" => "moon", 'laydate' => ['type' => 'month'])).
                        hidden(array("name" => "targetId", "value" => $this->get('id'))),
                ]
            ]
        ],1);
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

    /**
     * 员工页卡薪酬记录
     *
     * @return bool|string
     */
    public function salaryRecord(): bool|string
    {
        $html = $this->salaryRecordOptions(false);
        $button = "";
        //返回
        $json['html'] = $this->search($html, layout: 'pop', toolButton: $button);
        return json_encode($json, 320);
    }

    public function salaryRecordSearch(): bool|string
    {
        $id = $this->post('targetId');
        //全等查询数组
        $equal = array(
            'isPay'=>1,
            'month'=>$this->post('moon')
        );
        $like = array(
        );
        $and = " and stid = '$id'";
        //获取查询结果
        $where = search(array("=" => $equal, "like" => $like)) . $and;
        $page = $this->page(array("table" => self::table, "where" => $where, "order" => " month desc,time desc"));

        $_SESSION[self::page]['paySql'] = $page['fullSql'];
        $tr = '';
        //获取记录
        foreach ($page['array'] as $array) {
            $days = find(array('table'=>'work_sign','field'=>"count(distinct(date_format(signTime,'%Y-%m-%d'))) as day","single"=>"stid = '$array[stid]' and date_format(signTime,'%Y-%m') = '$array[month]'"))['day'];
            $income = $array['money']-$array['insure']-$array['providentFund'];
            $incomeAfterTax = $income-$array['personalTax'];
            $tr .= <<<eof
                 <tr>
                     <td>{$array['name']}</td>
                     <td>{$array['month']}</td>
                     <td>{$days}</td>
                     <td>{$array['lawDay']}</td>
                     <td>{$array['baseMoney']}</td>
                     <td>{$array['jobMoney']}</td>
                     <td>{$array['telFee']}</td>
                     <td>{$array['trafficFee']}</td>
                     <td>{$array['performance']}</td>
                     <td>{$array['pieceSalary']}</td>
                     <td>{$array['hourMoney']}</td>
                     <td>{$array['workAgeFee']}</td>
                     <td>{$array['educationFee']}</td>
                     <td>{$array['jobTitleFee']}</td>
                     <td>{$array['temperatureFee']}</td>
                     <td>{$array['overtimeFee']}</td>
                     <td>{$array['otherFee']}</td>
                     <td>{$array['fullAttendance']}</td>
                     <td>{$array['leaveMoney']}</td>
                     <td>{$array['lateMoney']}</td>
                     <td>{$array['otherDecMoney']}</td>
                     <td>{$array['money']}</td>
                     <td>{$array['agedFee']}</td>
                     <td>{$array['medicalFee']}</td>
                     <td>{$array['unemploymentFee']}</td>
                     <td>{$array['insure']}</td>
                     <td>{$array['personalTax']}</td>
                     <td>$income</td>
                     <td>{$array['decMoney']}</td>
                     <td>$incomeAfterTax</td>
                     <td>{$array['text']}</td>
                 </tr>
eof;
        }
        $thead = $this->tdHead();
        $html = <<<eof
<table id="subjectTable" class="tableMany">
   $thead
    <tbody>
     $tr
    </tbody>
</table>
<style>
#subjectTable td{white-space:nowrap}
#subjectTable{margin-left: 0;}
.listForm{overflow: auto;width: calc(100%);}
</style>
eof;

        //控件
        $button = "";
        //返回
        $json['html'] = $page['hint'] . $button . "<form class='listForm' name='recordForm'>" .$html . "</form>" . $page['button'];
        return json_encode($json, 320);
    }

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    L('salary.table.dan_ju_bian_hao') => text(array("name" => "orderNo")),
                    L('salary.table.yue_fen')     => text(array("name" => "month",'laydate' => ['type' => 'month'])),
                    L('salary.table.shen_qing_ren') => selectMultiple(array("name" => "staffId", "class" => 'width200','table'=>'staff','where'=>"1=1 order by orderNo asc",'sqlId'=>'stid','sqlField'=>'name')),
                ],
                [
                    L('salary.table.zhuang_tai') => select(["name" => "state", 'option' => ['草稿', '审核中', '已通过']]),
                ]
            ]
        ]);
        //返回
        if(!$isAsync){
            return $html;
        }else{
            return json_encode(['html'=>$html],320);
        }
    }

    /*列表-查询条件*/
    public function home()
    {
        $html = $this->homeOptions(false);
        //控件
        $button = "";
        $url = root . "control/adIndex.html?cla=" . self::page;
        if ($this->power(self::page, "edit")) {
            $button .= "<span onclick=\"layer('" . self::page . "','edit',{})\" class='spanButton'>新增</span>\n";
        }
        if ($this->power(self::page, "del")) {
            $button .= "<span class='spanButton' onclick=\"layer('{$this->get('cla')}', 'operate', {'act': 'del'})\">删除</span>\n";
        }
        //返回
        return $this->homeFun($this->search($html,layout: 'pop',toolButton: $button));
    }

    /**
     * 字段初始化
     */
    public function fieldInit($fun): array
    {
        switch ($fun) {
            default:
                $tr = [
                    'orderNo'      => [
                        'name'  => L('salary.table.dan_ju_bian_hao'),
                        'width' => 300,
                        'sort' => 1,
                    ],
                    'month' => [
                        'name'  => L('salary.table.yue_fen'),
                        'width' => 300,
                        'sort' => 1,
                    ],
                    'stid'  => [
                        'name'  => L('salary.table.shen_qing_ren'),
                        'width' => 300,
                    ],
                    'time'         => [
                        'name'  => L('salary.table.dan_ju_ri_qi'),
                        'width' => 300,
                        'sort' => 1,
                    ],
                    'state'          => [
                        'name'  => L('salary.table.zhuang_tai'),
                        'width' => 300,
                    ]
                ];
        }
        return $tr;
    }

    /*客户列表-查询结果*/
    public function homeSearch()
    {
        //like查询数组
        $like = array(
            "orderNo" => $this->post('orderNo'),
            "deptName" => $this->post('deptName'),
        );
        //全等查询数组
        $equal = array(
            "state" => $this->post('state'),
            "stid" => $this->post('staffId'),
            "month"=>$this->post('month')
        );
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'time',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
        //获取查询结果
        $where = search(array("like" => $like, "=" => $equal));

        $page = $this->page(array("table" => 'salary', "where" => $where, "order" => $orderBy['orderBy']));
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("listForm", "listId")
        );
        //获取记录
        $url = root . "control/adIndex.html?cla=" . self::page;
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate = array(
                "box" => array("name" => "listId", "value" => $array['id']),
                "detail" => array("title" => L('salary.table.salaryInfo'), "click" => "newIframe('" .L('salary.table.salaryInfo') . "','" . $url . "&fun=detail&id=" . $array['id'] . "')"),
                'print' => array('title' => L('salary.table.da_yin'), 'click' => "window.open('" . root . "control/adIndex.html?cla=" . self::page . "&fun=printPage&id={$array['id']}')"),
            );
            $liButton[] = $this->dominate($dominate);
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case "stid":
                        $row[] = self::findStaff($array['stid']);
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        //控件
        $button = "";
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton,"width" => 120),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
        ));
        //返回
        $json['html'] = $page['hint'] . $button . "<form name='listForm'>" . $li . "</form>" . $page['button'] . clear;
        return json_encode($json, 320);
    }
    public function edit(): bool|string
    {
        //生成表单
        $html = $this->layerEdit(array(
            "table" => array(
                array(
                    must.L('salary.table.yue_fen')."：" => text(array('name'=>'month','laydate'=>['type'=>'month'],'value'=>date('Y-m'))),
                ),
            )
        ));
        //返回
        return $this->layer(array("title" => L('salary.table.xin_zeng'), "height" => 165, "html" => $html));
    }

    public function editEdit(){
        $field = [
            'month'=>$this->post('month')
        ];
        if (!$this->power(self::page, "edit")) {
            $json['warn'] =L('salary.table.salary_edit_permission');
        } elseif (empty($field['month'])) {
            $json['warn'] = L('salary.table.qxzyf');
        } elseif (static::total(array('table'=>'salary','where'=>"month = '$field[month]'")) >0) {
            $json['warn'] = L('salary.table.yczcyfdgzb');
        } else {
            $department = query('department',"id = '".$this->controlJob['departmentId']."'");
            $userNo = codeTemplateClass::generateCode(self::page,[
                'prefix' => 'GZT' . date('Ymd'),
                'table' => 'salary',
                'field' => 'orderNo',
                'where' => '',
            ],$field);
            $field = array_merge($field,[
                'id'=>suiji(),
                'stid'=>self::$stid,
                'deptName'=>$department['name'],
                'state'=>'草稿',
                'orderNo'=>$userNo
            ]);
            $json['warn'] = insert(array('table' =>'salary', 'field' => $field));
            if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                //添加日志
                $text = str_replace(['{{staffName}}','{{orderNo}}','{{id}}'],[$this->control['name'],$field['orderNo'],$field['id']],L('salary.table.salary_edit_text'));
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = L('salary.table.new_success');
                $json['warn'] = 2;
            }
        }
        //返回
        return json_encode($json, 320);
    }


    /**
     * 审核按钮
     * @param $info
     * @return array
     */
    public function auditButton($info): array
    {
        $button=[];
        if ($info['state'] == '草稿' || auditClass::auditFlag('salary', $info['id'],'selfChoose')) {
            $button[] = [
                "name" => L('salary.table.ti_jiao_shen_pi'),
                "type" => "弹出层",
                "cla" => 'audit',
                "fun" => "operate",
                'style' => 'li-btn-blue-bg',
                "post" => ["act" => 'start', "id" => $info['id'], 'body' => self::encryptDecrypt(json_encode([
                    'name'=>'工资条',
                    'table' => 'salary',
                    'process' => [
                        'detail'=>[
                            'cla' => $this->get('cla'),
                            'fun' => 'detail'
                        ],
                        //执行发起时验证函数
                        'before' => [
                            'cla' => $this->get('cla'),
                            'fun' => ''
                        ],
                        //完成发起后执行函数
                        'after' => [
                            'cla' => $this->get('cla'),
                            'fun' => ''
                        ],
                    ],
                ], 320))],
            ];
        }
// 审批并判断是否有权限
        if ($info['state'] == '审核中' && auditClass::auditFlag('salary', $info['id'])) {
            $button[] = [
                "name" => L('salary.table.tjspr'),
                "type" => "弹出层",
                "cla" => 'audit',
                "fun" => "operate",
                "post" => ["act" => 'addApprover', "id" => $info['id'],  'body' => self::encryptDecrypt(json_encode([
                    'table' => 'salary'
                ], 320))],
            ];
            $button[] = [
                "name" => L('salary.table.zhuan_jiao'),
                "type" => "弹出层",
                "cla" => 'audit',
                "fun" => "operate",
                "post" => ["act" => 'transfer', "id" => $info['id'], 'body' => self::encryptDecrypt(json_encode([
                    'table' => 'salary',
                ], 320))],
            ];
            $button[] = [
                "name" => L('salary.table.shen_pi'),
                "type" => "弹出层",
                "cla" => 'audit',
                "fun" => "operate",
                // 以下参数固定格式
                "post" => ["act" => 'approval', "id" => $info['id'], 'body' => self::encryptDecrypt(json_encode([
                    'table' => 'salary',
                    // 当前状态
                    'state' => $info['state'],
                    // 变更
                    'field' => ['state'],   //变更字段 可多个
                    'value' => [
                        'state' => ['草稿', '已通过'],
                    ],
                    // 审核时回调
                    'process' => [
                        //执行首次审核时验证
                        'before' => [
                            'cla' => $this->get('cla'),
                            'fun' => ''
                        ],
                        //执行末次审核后处理
                        'after' => [
                            'cla' => $this->get('cla'),
                            'fun' => ''
                        ],
                    ],
                ], 320))],
                'style' => 'li-btn-blue-bg',
            ];
        }

        // 撤销审批
        if (auditClass::auditFlag(   'salary', $info['id'],'cancel') && $info['state'] != '草稿') {
            $button[] = [
                "name" => L('salary.table.cxsp'),
                "type" => "弹出层",
                "cla" => 'audit',
                "fun" => "operate",
                "post" => ["act" => 'cancel', "id" => $info['id'], 'body' => self::encryptDecrypt(json_encode([
                    'table' => 'salary',
                    // 当前状态
                    'state' => $info['state'],
                    // 变更
                    'field' => ['state'],   //变更字段 可多个
                    'value' => [
                        'state' => ['草稿'],
                    ],
                    'process' => [
                        //完成发起后执行函数
                        'after' => [
                            'cla' => $this->get('cla'),
                            'fun' => ''
                        ],
                    ],
                ], 320))],
            ];
        }
        return $button;
    }
    /*详情页*/
    public function detail(): string
    {
        $info = query('salary', " id = '{$this->get('id')}'");
        if (empty($info['id'])) {
            $html =L('salary.table.wzdcgzt');
        } else {
            $audit = query('audit'," targetId = '$info[id]'");
            //菜单
            $data = array(
                "id" => $info['id'],
                'menu'=>[
                    'detail'=>L('salary.table.ji_ben_xin_xi'),
                    'waitPay'=>L('salary.table.dai_bo_fu'),
                    'deduction'=>L('salary.table.yi_bo_fu')
                ]
            );
            //审核按钮
            $button =$this->auditButton($info);
            if ($this->power(self::page, "edit") && $info['state'] == '草稿'){
                //按钮
                $button[] = [
                    "name" => L('salary.table.shan_chu'),
                    "type" => "弹出层",
                    "cla" => $this->get('cla'),
                    "fun" => "operate",
                    "post" => ["act" => 'del', "id" => $info['id']],
                ];
            }

            //生成表单
            $data['button'] = $this->tableShowButton($button);
            $data['html'] = $this->tableShow(array(
                "基本信息" => array(
                    array(
                        L('salary.table.dan_ju_bian_hao') => $info['orderNo'],
                        L('salary.table.yue_fen') => $info['month'],
                        L('salary.table.sqrbm') => $info['deptName'],
                        L('salary.table.shen_qing_ren') => self::findStaff($info['stid']),
                    ),
                    array(
                        L('salary.table.cjsj') => $info['time'],
                        L('salary.table.tjsj') => self::null($audit['commitTime']),
                        L('salary.table.zhuang_tai') => $info['state'],
                    ),
                ),
                L('salary.table.fu_jian') => array(
                    array(
                        fileUploadClass::showFile($info['id'])
                    )
                ),
                L('salary.table.liu_cheng') => array(
                    array(
                        auditClass::auditRecord('salary', $info['id'])
                    )
                ),

            ));
            //生成页面
            $html = $this->tab($data);
        }
        //返回
        return $html;
    }

    /*列表页-查询条件*/
    public function deductionOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    L('salary.table.xing_ming') => text(array("name" => "staffName")),
                    L('salary.table.bu_men')   => selectMultiple(["name" => "departmentId", 'table' => " department", 'sqlId' => 'id', 'sqlField' => 'name', 'class' => 'width200']).
                        hidden(array('name'=>'id','value'=>$this->get('id'))),
                ]
            ]
        ],1);
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

    public function deduction()
    {
        $html = $this->deductionOptions(false);
        //控件
        $button = "";
        if ($this->power(self::page, "export")) {
            $button .="<span class='spanButton' onclick=\"layer('importTemplate','exportFrame',{cla:'".self::page."',exportFun:'exportPay',classify:'已拨付'})\">导出</span>";
            $button .= "  <a href='" . root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=exportPay'><span class='spanButton'>".L('salary.table.export')."</span></a>\n";
        }
        $json['html'] = $this->search($html, layout: 'pop', toolButton: $button);
        return json_encode($json, 320);
    }

    public function deductionSearch()
    {
        $info = query('salary',"id = '".$this->post('id')."'");
        //全等查询数组
        $equal = array(
            'isPay'=>1
        );
        $like = array(
            "name" => $this->post('staffName'),//员工
        );
        $and = " and month = '$info[month]'";
        if (!empty($this->post('departmentId'))) {
            //部门
            $and .= " and jobId in (select id from job where departmentId = '{$this->post('departmentId')}') ";
        }
        //获取查询结果
        $where = search(array("=" => $equal, "like" => $like)) . $and;
        $page = $this->page(array("table" => self::table, "where" => $where, "order" => " month desc,time desc"));

        $_SESSION[self::page]['paySql'] = $page['fullSql'];
        $tr = '';
        //获取记录
        foreach ($page['array'] as $array) {
            $staff = query('staff',"stid = '$array[stid]'");
            $talentPool = query('talent_pool',"id = '$staff[talentId]'");
            $days = find(array('table'=>'work_sign','field'=>"count(distinct(date_format(signTime,'%Y-%m-%d'))) as day","single"=>"stid = '$array[stid]' and date_format(signTime,'%Y-%m') = '$array[month]'"))['day'];
            //找当月的奖惩金额
            $rewards = find(['table'=>'rewards','where'=>"staffId = '$array[stid]' and date_format(recordDate,'%Y-%m') ='$array[month]' and state = '已通过'",'sum'=>"money"]);
            $array['money'] = $array['money']+$rewards;
            $income = $array['money']-$array['insure']-$array['providentFund'];
            $incomeAfterTax = $income-$array['personalTax'];
            $tr .= <<<eof
                 <tr>
                     <td><label class="listCheckbox"><input name="listId[]" type="checkbox" value="$array[id]"><span></span></label></td>
                     <td>{$array['name']}</td>
                     <td>{$array['month']}</td>
                     <td>{$days}</td>
                     <td>{$array['lawDay']}</td>
                     <td>{$array['baseMoney']}</td>
                     <td>{$array['jobMoney']}</td>
                     <td>{$array['telFee']}</td>
                     <td>{$array['trafficFee']}</td>
                     <td>{$array['performance']}</td>
                      <td>{$array['pieceSalary']}</td>
                      <td>{$array['hourMoney']}</td>
                     <td>{$array['workAgeFee']}</td>
                     <td>{$array['educationFee']}</td>
                     <td>{$array['jobTitleFee']}</td>
                     <td>{$array['temperatureFee']}</td>
                     <td>{$array['overtimeFee']}</td>
                     <td>{$array['otherFee']}</td>
                      <td>{$array['fullAttendance']}</td>
                     <td>{$array['leaveMoney']}</td>
                     <td>{$array['lateMoney']}</td>
                     <td>{$array['otherDecMoney']}</td>
                       <td>{$array['liveFee']}</td>
                         <td>{$rewards}</td>
                     <td>{$array['money']}</td>
                     <td>{$array['agedFee']}</td>
                     <td>{$array['medicalFee']}</td>
                     <td>{$array['unemploymentFee']}</td>
                     <td>{$array['insure']}</td>
                     <td>{$array['providentFund']}</td>
                     <td>$income</td>
                     <td>{$array['personalTax']}</td>
                     <td>$incomeAfterTax</td>
                     <td>{$array['text']}</td>
                     <td>{$talentPool['idCard']}</td>
                     <td>{$talentPool['tel']}</td>
                 </tr>
eof;
        }

        $thead = $this->tdHead();
        $html = <<<eof
<table id="subjectTable" class="tableMany">
    $thead
    <tbody>
     {$tr}
    </tbody>
</table>
<style>
#subjectTable td{white-space:nowrap}
#subjectTable{margin-left: 0;}
.listForm{overflow: auto;width: calc(100%);padding: 10px 0}
</style>
eof;

        //控件
        $button = "";
        //返回
        $json['html'] = $page['hint'] . $button . "<form class='listForm' name='recordForm'>" .$html . "</form>" . $page['button'];
        return json_encode($json, 320);
    }

    /**
     * 导出已拨付
     */
    public function exportPay()
    {
        $templateId = $this->get('templateId');
        $checkedId = $this->get('checkedId')?explode(',',$this->get('checkedId')):[];
        if (!$this->power(self::page, 'export')) {
            $_SESSION['warn'] = L('salary.table.nhmzdcdzx');
        } else {
            $data = [];
            /***********标题**********/
            $title =[];
            $tempFieldAll = importTemplateClass::templateField(self::page, 'exportFieldInit', id:$templateId);
            foreach ($tempFieldAll as $array) {
                if ($array['display']){
                    $title[] = $array['aliasName'];
                }
            }
            //判断是否选中导出
            if (!self::is_null_array($checkedId)){
                $result = find(array(
                    "table" => self::table,
                    "where" => "id in ('".implode("','", $checkedId)."') and isPay = 1 order by month desc",
                ))['array'];
            }else{
                $sql   = $_SESSION[self::page]['paySql'];
                $result   = sqlFind($sql);
            }
            //导出数据生成
            foreach ($result as $array){
                $column = [];
                $job = query('job', " id = '$array[jobId]'");
                $department = query('department', " id = '$job[departmentId]'");
                //找当月的奖惩金额
                $rewards = find(['table'=>'rewards','where'=>"staffId = '$array[stid]' and date_format(recordDate,'%Y-%m') ='$array[month]' and state = '已通过'",'sum'=>"money"]);
                $staff = query('staff',"stid = '$array[stid]'");
                $talentPool = query('talent_pool',"id = '$staff[talentId]'");
                $days = find(array('table'=>'work_sign','field'=>"count(distinct(date_format(signTime,'%Y-%m-%d'))) as day","single"=>"stid = '$array[stid]' and date_format(signTime,'%Y-%m') = '$array[month]'"))['day'];
                $array['money']+=$rewards;
                $income = $array['money']-$array['insure']-$array['providentFund'];
                $incomeAfterTax = $income-$array['personalTax'];
                foreach ($tempFieldAll as $templateField){
                    if ($templateField['display']){
                        $column[] = match ($templateField['columnName']){
                            '部门'=>$department['name'],
                            '职位'=>$job['name'],
                            '姓名'=>$array['name'],
                            '身份证号'=>$talentPool['idCard'],
                            '手机号'=>$talentPool['tel'],
                            '月份'=>$array['month'],
                            '实际出勤天数'=>$days,
                            '应出勤天数'=>$array['lawDay'],
                            '基本工资'=>$array['baseMoney'],
                            '岗位工资'=>$array['jobMoney'],
                            '通讯补贴'=>$array['telFee'],
                            '交通补贴'=>$array['trafficFee'],
                            '绩效工资'=>$array['performance'],
                            '计件工资'=>$array['pieceSalary'],
                            '计时工资'=>$array['hourMoney'],
                            '工龄工资'=>$array['workAgeFee'],
                            '学历津贴'=>$array['educationFee'],
                            '职称津贴'=>$array['jobTitleFee'],
                            '高温补贴'=>$array['temperatureFee'],
                            '加班补贴'=>$array['overtimeFee'],
                            '其他补贴'=>$array['otherFee'],
                            '全勤奖'=>$array['fullAttendance'],
                            '病事假扣款'=>$array['leaveMoney'],
                            '迟到早退'=>$array['lateMoney'],
                            '其他扣款'=>$array['otherDecMoney'],
                            '住宿费用'=>$array['liveFee'],
                            '奖惩金额'=>$rewards,
                            '应发工资'=>$array['money'],
                            '养老保险'=>$array['agedFee'],
                            '医疗保险'=>$array['medicalFee'],
                            '失业保险'=>$array['unemploymentFee'],
                            '社保小计'=>$array['insure'],
                            '公积金'=>$array['decMoney'],
                            '代扣个人所得税'=>$array['providentFund'],
                            '税后应得'=>$incomeAfterTax,
                            '实发'=>$array['payMoney'],
                            '备注'=>$array['text'],
                            default=>'',
                        };
                    }
                }
                $data[] = $column;
            }
            $text = str_replace(['{{staffName}}'],[$this->control['name']],L('salary.table.paySlipExport'));
            $this->logText(["type" => self::page, "text" => $text]);
            $this->excelOut($title, $data, L('salary.table.payedSlip').".xlsx");
            exit(0);
        }
        header("Location:" . getenv("HTTP_REFERER"));

    }

    /*列表页-查询条件*/
    public function waitPayOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    L('salary.table.xing_ming') => text(array("name" => "staffName")),
                    L('salary.table.bu_men')   => selectMultiple(["name" => "departmentId", 'table' => " department", 'sqlId' => 'id', 'sqlField' => 'name', 'class' => 'width200']).
                        hidden(array('name'=>'id','value'=>$this->get('id'))),
                ]
            ]
        ],1);
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

    public function waitPay()
    {
        $html = $this->waitPayOptions(false);
        //控件
        $button = "";
        //导出
        if ($this->power(self::page, "export")) {
            $button .="<span class='spanButton' onclick=\"layer('importTemplate','exportFrame',{cla:'".self::page."'})\">导出</span>";
        }
        if ($this->power(self::page, "pay")) {
            $button .= "<span class='spanButton' onclick=\"layer('{$this->get('cla')}', 'pay', {})\">".L('salary.table.batchPay')."</span>\n";
        }
        $json['html'] = $this->search($html, layout: 'pop', toolButton: $button);
        return json_encode($json, 320);
    }
    public function waitPaySearch()
    {
        $info = query('salary',"id = '".$this->post('id')."'");
        //全等查询数组
        $equal = array(
            'isChecked'=>1
        );
        $like = array(
            "name" => $this->post('staffName'),//员工
        );
        $and = " and isPay = 0 and month = '{$info['month']}'";
        if (!empty($this->post('departmentId'))) {
            //部门
            $and .= " and jobId in (select id from job where departmentId = '{$this->post('departmentId')}') ";
        }
        //排序
        $orderBy = $this->orderBy(array(
            "search" => $this->post('orderBy')??null,
            "default" => '月份降序',
            "array" => array(
                "month" => array("desc" => '月份降序', "site" => 5),
            ),
        ));
        //获取查询结果
        $where = search(array("=" => $equal, 'like' => $like)) . $and;
        $page = $this->page(array("table" => self::table, "where" => $where, "order" => $orderBy['orderBy']));
        $_SESSION[self::page]['sql'] = $page['fullSql'];
        //获取表头
        $tr='';
        //获取记录
        foreach ($page['array'] as $array) {
            //找当月的奖惩金额
            $rewards = find(['table'=>'rewards','where'=>"staffId = '$array[stid]' and date_format(recordDate,'%Y-%m') ='$array[month]' and state = '已通过'",'sum'=>"money"]);

            //社保扣款(找缴款月份为这个月的)
            $insure = query('insure', " stid = '$array[stid]' and payMoon = '$array[month]'");
            $insure['personal'] = $insure['personal']?:0;
            //公积金扣款
            $providentFund = query('provident_fund', " staffId = '$array[stid]' and month = '$array[month]' and isCommit = 1");
            $providentFund['decMoney'] = $providentFund['decMoney']?:0;
            //个税扣款
            $personalTax = query('personal_tax', " staffId = '$array[stid]' and month = '$array[month]' and isCommit = 1");
            $personalTax['decMoney'] = $personalTax['decMoney']?:0;
            //判断是否属于停薪留职
            $staffStayRecord = find(array('table'=>'staff_stay_record','where'=>" state = '已通过' and isConfirm = 1 and date_format(confirmDate,'%Y-%m') <='$array[month]' and staffId = '$array[stid]' and if(recoverTime is null,1=1,date_format(recoverTime,'%Y-%m') >='$array[month]')"));
            $text = '';
            if (is_array($staffStayRecord['array'])){
                foreach ($staffStayRecord['array'] as $val){
                    $text.="停薪留职【{$val['confirmDate']}】起".(strtotime($val['recoverTime'])>0?"，【".date('Y-m-d',strtotime($val['recoverTime']))."】止":'');
                }
            }
            $text .= $providentFund['text'] ? $providentFund['text'] . '，' : '';
            $text .= $personalTax['text'] ? $personalTax['text'] . '，' : '';
            $text .= $array['text'] ? $array['text'] . '，' : '';
//            $text = text(array('name' => "text[$array[id]]", 'class' => 'text', 'blur' => "setText", 'other' => " data-name='payText'", 'value' => ));
            $staff = query('staff',"stid = '$array[stid]'");
            $talentPool = query('talent_pool',"id = '$staff[talentId]'");
            $yanglao = find(array('table' => 'insure', 'single' => "moon = '$array[month]' and subject = '养老保险'  and stid ='$array[stid]'", 'field' => "ifnull(sum(personal),0) as money"));
            $yiliao = find(array('table' => 'insure', 'single' => "moon = '$array[month]' and subject = '基本医疗'  and stid ='$array[stid]'", 'field' => "ifnull(sum(personal),0) as money"));
            $shiye = find(array('table' => 'insure', 'single' => "moon = '$array[month]' and subject = '失业保险'  and stid ='$array[stid]'", 'field' => "ifnull(sum(personal),0) as money"));
            $days = find(array('table'=>'work_sign','field'=>"count(distinct(date_format(signTime,'%Y-%m-%d'))) as day","single"=>"stid = '$array[stid]' and date_format(signTime,'%Y-%m') = '$array[month]'"))['day'];
            $array['money'] = $array['money']+$rewards;
            $income = $array['money']-$insure['personal']-$providentFund['decMoney'];
            $incomeAfterTax = $income-$personalTax['decMoney'];
            $tr .= <<<eof
                 <tr>
                     <td><label class="listCheckbox"><input name="listId[]" type="checkbox" value="$array[id]"><span></span></label></td>
                     <td>{$array['name']}</td>
                     <td>{$array['month']}</td>
                     <td>{$days}</td>
                     <td>{$array['lawDay']}</td>
                     <td>{$array['baseMoney']}</td>
                     <td>{$array['jobMoney']}</td>
                     <td>{$array['telFee']}</td>
                     <td>{$array['trafficFee']}</td>
                     <td>{$array['performance']}</td>
                     <td>{$array['pieceSalary']}</td>
                     <td>{$array['hourMoney']}</td>
                     <td>{$array['workAgeFee']}</td>
                     <td>{$array['educationFee']}</td>
                     <td>{$array['jobTitleFee']}</td>
                     <td>{$array['temperatureFee']}</td>
                     <td>{$array['overtimeFee']}</td>
                     <td>{$array['otherFee']}</td>
                     <td>{$array['fullAttendance']}</td>
                     <td>{$array['leaveMoney']}</td>
                     <td>{$array['lateMoney']}</td>
                     <td>{$array['otherDecMoney']}</td>
                     <td>{$array['liveFee']}</td>
                     <td>{$rewards}</td>
                     <td>{$array['money']}</td>
                     <td>{$yanglao['money']}</td>
                     <td>{$yiliao['money']}</td>
                     <td>{$shiye['money']}</td>
                     <td>{$insure['personal']}</td>
                     <td>{$providentFund['decMoney']}</td>
                     <td>$income</td>
                     <td>{$personalTax['decMoney']}</td>
                     <td>$incomeAfterTax</td>
                     <td>$text</td>
                     <td>{$talentPool['idCard']}</td>
                     <td>{$talentPool['tel']}</td>
                 </tr>
eof;
        }
        $thead = $this->tdHead();
        $html = <<<eof
<table id="subjectTable" class="tableMany">
    $thead
    <tbody>
     {$tr}
    </tbody>
</table>
<style>
#subjectTable td{white-space:nowrap}
#subjectTable{margin-left: 0;}
.listForm{overflow: auto;width: calc(100%);padding: 10px 0}
</style>
eof;



        //控件
        $button = "";
        //返回
        $json['html'] = $page['hint'] . $button . "<form class='listForm' name='listForm'>" . $html . "</form>" . $page['button'];

        $json['html'] .= <<<eof
<script>
         function setText (obj){
         let id = $(obj).parent().parent().find("input[name='listId[]']").val();
         let name = $(obj).data('name');
         let val = $(obj).val();
            $.post(root+'control/adIndex.html?cla={$this->get('cla')}&fun=setText',{id:id, name:name,val:val},function(res) {
                if(res.warn !== 1){
                   warn(res.warn)
                }else{
                    let total = $(obj).parent().parent().find(".totalMoney").html();
                    total = total*1;
                    if (name=='adjustmentMoney'){
                        $(obj).parent().parent().find(".totalMoney").html((total+res.data.diff).toFixed(2));
                    }
                }
            },'json')
    }
</script>
eof;

        return json_encode($json, 320);
    }

    public function tdHead(): string
    {
        $name = L('staffProfiles.table.name');
        $month = L('performance.table.month');
        $sjcqts = L('salary.table.sjcqts');
        $ycqts= L('salary.table.ycqts');
        $structureDetails = L('salary.table.structureDetails');
        $socialFundDetail = L('salary.table.socialFundDetail');
        $income = L('salary.table.income');
        $shi_fa = L('salary.table.shi_fa');
        $bei_zhu = L('salary.table.bei_zhu');
        $idCard = L('salary.table.idCard');
        $shou_ji_hao = L('salary.table.shou_ji_hao');
        $ji_ben_gong_zi = L('salary.table.ji_ben_gong_zi');
        $gwgz = L('salary.table.gwgz');
        $tong_xun_bu_tie = L('salary.table.tong_xun_bu_tie');
        $jtbt = L('salary.table.jtbt');
        $ji_xiao_gong_zi = L('salary.table.ji_xiao_gong_zi');
        $ji_jian_gong_zi = L('salary.table.ji_jian_gong_zi');
        $ji_shi_gong_zi = L('salary.table.ji_shi_gong_zi');
        $glgz = L('salary.table.glgz');
        $xue_li_jin_tie = L('salary.table.xue_li_jin_tie');
        $zcjt = L('salary.table.zcjt');
        $gao_wen_bu_tie = L('salary.table.gao_wen_bu_tie');
        $jia_ban_bu_tie = L('salary.table.jia_ban_bu_tie');
        $qi_ta_bu_tie = L('salary.table.qi_ta_bu_tie');
        $bsjkk = L('salary.table.bsjkk');
        $chi_dao_zao_tui = L('salary.table.chi_dao_zao_tui');
        $qi_ta_kou_kuan = L('salary.table.qi_ta_kou_kuan');
        $zxfy = L('salary.table.zxfy');
        $jcfy = L('salary.table.jcfy');
        $ying_fa_gong_zi = L('salary.table.ying_fa_gong_zi');
        $quan_qin_jiang = L('salary.table.quan_qin_jiang');
        $ylbx = L('salary.table.ylbx');
        $medical_insurancei = L('salary.table.medical_insurance');
        $shi_ye_bao_xian = L('salary.table.shi_ye_bao_xian');
        $she_bao_xiao_ji = L('salary.table.she_bao_xiao_ji');
        $gong_ji_jin = L('salary.table.gong_ji_jin');
        $dkgrzds = L('salary.table.dkgrzds');
        $shyd = L('salary.table.shyd');
        return <<<eof
<thead>
        <tr>
            <td rowspan="2" style="vertical-align:middle"><label title='全选' class="listCheckbox"><input type="checkbox" form="listForm" name="listId" onchange="checkAll(this)"><span></span></label></td>
            <td rowspan="2" style="vertical-align:middle">$name</td>
            <td rowspan="2" style="vertical-align:middle">$month</td>
            <td rowspan="2" style="vertical-align:middle">$sjcqts</td>
            <td rowspan="2" style="vertical-align:middle">$ycqts</td>
            <td colspan="20" class="center">$structureDetails</td>
            <td colspan="5" class="center">$socialFundDetail</td>
            <td rowspan="2" style="vertical-align:middle" class="center">$income</td>
            <td colspan="2" class="center">$shi_fa</td>
            <td rowspan="2" style="vertical-align:middle" class="center">$bei_zhu</td>
            <td rowspan="2" style="vertical-align:middle" class="center">$idCard</td>
            <td rowspan="2" style="vertical-align:middle" class="center">$shou_ji_hao</td>
        </tr>
        <tr>
            <td>$ji_ben_gong_zi</td><td>$gwgz</td>
            <td>$tong_xun_bu_tie</td><td>$jtbt</td>
            <td>$ji_xiao_gong_zi</td><td>$ji_jian_gong_zi</td><td>$ji_shi_gong_zi</td><td>$glgz</td>
            <td>$xue_li_jin_tie</td><td>$zcjt</td>
            <td>$gao_wen_bu_tie</td><td>$jia_ban_bu_tie</td>
            <td>$qi_ta_bu_tie</td><td>$quan_qin_jiang</td><td>$bsjkk</td>
            <td>$chi_dao_zao_tui</td><td>$qi_ta_kou_kuan</td><td>$zxfy</td><td>$jcfy</td>
            <td>$ying_fa_gong_zi</td><td>$ylbx</td>
            <td>$medical_insurancei</td><td>$shi_ye_bao_xian</td>
            <td>$she_bao_xiao_ji</td><td>$gong_ji_jin</td><td>$dkgrzds</td>
            <td>$shyd</td>
        </tr>
    </thead>
eof;

    }

    /**
     * 填写备注或调整金额
     * @return bool|string
     */
    public function setText()
    {
        $diff = 0;
        $id = $this->post('id');
        $name = $this->post('name');
        $val = $this->post('val');
        $info = query(self::table, " id = '{$id}' ");
        if (!$this->power(self::page, 'edit')) {
            $json['warn'] = L('salary.table.nhmzbjdzx');
        } elseif (!$info['id']) {
            $json['warn'] = L('salary.table.wzdcgzt');
        } elseif ($info['isPay'] == 1) {
            $json['warn'] = L('salary.table.cgztybfbnxg');
        } elseif (empty($name)) {
            $json['warn'] = L('salary.table.wzdgglx');
        } else {
            $field = [
                $name => $val,
                'updateTime' => $this->time,
            ];
            if ($name == 'adjustmentMoney') {
                $diff = $val - $info['adjustmentMoney'];
            }
            $json['warn'] = update([
                'table' => self::table,
                'field' => $field,
                'where' => " id = '$id' "
            ]);
            if ($json['warn'] == '更新成功') {
                $json['warn'] = 1;
            }

        }
        $json['data']['diff'] = $diff;
        return json_encode($json, 320);
    }

    public function exportData()
    {
        $templateId = $this->get('templateId');
        $checkedId = $this->get('checkedId')?explode(',',$this->get('checkedId')):[];
        if (!$this->power(self::page, 'export')) {
            $_SESSION['warn'] = L('salary.table.nhmzdcdzx');
        } else {
            $data = [];
            /***********标题**********/
            $title =[];
            $tempFieldAll = importTemplateClass::templateField(self::page, 'exportFieldInit', id:$templateId);
            foreach ($tempFieldAll as $array) {
                if ($array['display']){
                    $title[] = $array['aliasName'];
                }
            }
            //判断是否选中导出
            if (!self::is_null_array($checkedId)){
                $result = find(array(
                    "table" => self::table,
                    "where" => "id in ('".implode("','", $checkedId)."') and isPay = 0 order by month desc",
                ))['array'];
            }else{
                $sql   = $_SESSION[self::page]['sql'];
                $result   = sqlFind($sql);
            }
            //导出数据生成
            foreach ($result as $array){
                $column = [];
                $job = query('job', " id = '$array[jobId]'");
                $department = query('department', " id = '$job[departmentId]'");
                //找当月的奖惩金额
                $rewards = find(['table'=>'rewards','where'=>"staffId = '$array[stid]' and date_format(recordDate,'%Y-%m') ='$array[month]' and state = '已通过'",'sum'=>"money"]);

                //社保扣款(找缴款月份为这个月的)
                $insure = query('insure', " stid = '$array[stid]' and payMoon = '$array[month]'");
                $insure['personal'] = $insure['personal']?:0;
                //公积金扣款
                $providentFund = query('provident_fund', " staffId = '$array[stid]' and month = '$array[month]' and isCommit = 1");
                $providentFund['decMoney'] = $providentFund['decMoney']?:0;
                //个税扣款
                $personalTax = query('personal_tax', " staffId = '$array[stid]' and month = '$array[month]' and isCommit = 1");
                $personalTax['decMoney'] = $personalTax['decMoney']?:0;
                //判断是否属于停薪留职
                $staffStayRecord = find(array('table'=>'staff_stay_record','where'=>" state = '已通过' and isConfirm = 1 and date_format(confirmDate,'%Y-%m') <='$array[month]' and staffId = '$array[stid]' and if(recoverTime is null,1=1,date_format(recoverTime,'%Y-%m') >='$array[month]')"));
                $text = '';
                if (is_array($staffStayRecord['array'])){
                    foreach ($staffStayRecord['array'] as $val){
                        $text.="停薪留职【{$val['confirmDate']}】起".(strtotime($val['recoverTime'])>0?"，【".date('Y-m-d',strtotime($val['recoverTime']))."】止":'');
                    }
                }
                $text .= $insure['text'] ? $insure['text'] . '，' : '';
                $text .= $providentFund['text'] ? $providentFund['text'] . '，' : '';
                $text .= $personalTax['text'] ? $personalTax['text'] . '，' : '';
                $text .= $array['text'] ? $array['text'] . '，' : '';
                $staff = query('staff',"stid = '$array[stid]'");
                $talentPool = query('talent_pool',"id = '$staff[talentId]'");
                $yanglao = find(array('table' => 'insure', 'single' => "moon = '$array[month]' and subject = '养老保险'  and stid ='$array[stid]'", 'field' => "ifnull(sum(personal),0) as money"));
                $yiliao = find(array('table' => 'insure', 'single' => "moon = '$array[month]' and subject = '基本医疗'  and stid ='$array[stid]'", 'field' => "ifnull(sum(personal),0) as money"));
                $shiye = find(array('table' => 'insure', 'single' => "moon = '$array[month]' and subject = '失业保险'  and stid ='$array[stid]'", 'field' => "ifnull(sum(personal),0) as money"));
                $days = find(array('table'=>'work_sign','field'=>"count(distinct(date_format(signTime,'%Y-%m-%d'))) as day","single"=>"stid = '$array[stid]' and date_format(signTime,'%Y-%m') = '$array[month]'"))['day'];
                $array['money']+=$rewards;
                $income = $array['money']-$insure['personal']-$providentFund['decMoney'];
                $incomeAfterTax = $income-$personalTax['decMoney'];
                foreach ($tempFieldAll as $templateField){
                    if ($templateField['display']){
                        $column[] = match ($templateField['columnName']){
                            '部门'=>$department['name'],
                            '职位'=>$job['name'],
                            '姓名'=>$array['name'],
                            '身份证号'=>$talentPool['idCard'],
                            '手机号'=>$talentPool['tel'],
                            '月份'=>$array['month'],
                            '实际出勤天数'=>$days,
                            '应出勤天数'=>$array['lawDay'],
                            '基本工资'=>$array['baseMoney'],
                            '岗位工资'=>$array['jobMoney'],
                            '通讯补贴'=>$array['telFee'],
                            '交通补贴'=>$array['trafficFee'],
                            '绩效工资'=>$array['performance'],
                            '计件工资'=>$array['pieceSalary'],
                            '计时工资'=>$array['hourMoney'],
                            '工龄工资'=>$array['workAgeFee'],
                            '学历津贴'=>$array['educationFee'],
                            '职称津贴'=>$array['jobTitleFee'],
                            '高温补贴'=>$array['temperatureFee'],
                            '加班补贴'=>$array['overtimeFee'],
                            '其他补贴'=>$array['otherFee'],
                            '全勤奖'=>$array['fullAttendance'],
                            '病事假扣款'=>$array['leaveMoney'],
                            '迟到早退'=>$array['lateMoney'],
                            '其他扣款'=>$array['otherDecMoney'],
                            '住宿费用'=>$array['liveFee'],
                            '奖惩金额'=>$rewards,
                            '应发工资'=>$array['money'],
                            '养老保险'=>$yanglao['money'],
                            '医疗保险'=>$yiliao['money'],
                            '失业保险'=>$shiye['money'],
                            '社保小计'=>$insure['personal'],
                            '公积金'=>$providentFund['decMoney'],
                            '代扣个人所得税'=>$personalTax['decMoney'],
                            '税后应得'=>$incomeAfterTax,
                            '备注'=>$text,
                            default=>'',
                        };
                    }
                }
                $data[] = $column;
            }


            $text = str_replace(['{{staffName}}'],[$this->control['name']],L('salary.table.waitPaySlipExport'));
            $this->logText(["type" => self::page, "text" => $text]);
            $this->excelOut($title, $data, L('salary.table.waitPayedSlip').".xlsx");
            exit(0);
        }
        header("Location:" . getenv("HTTP_REFERER"));

    }

    /**
     * 拨付
     * @return bool|string
     */
    public function pay()
    {
        //生成表单
        $html = $this->layerEdit(array("table" => array(
            array(
                L('salary.table.ti_shi') => L('salary.table.payWarn'),
            ),
        )));
        //返回
        return $this->layer(array("title" => L('salary.table.bo_fu'), "height" => 160, "width" => 600, "html" => $html, 'formTwo' => 'listForm'));
    }

    /**
     * 拨付编辑
     * @return bool|string
     */
    public function payEdit()
    {
        $listId = $this->post('listId');
        if (!$this->power(self::page, "pay")) {
            $json['warn'] = L('salary.table.payPermission');
        } elseif (empty($listId) || !is_array($listId)) {
            $json['warn'] = L('salary.table.qxzsj');
        }else {
            $x = 0;
            foreach ($listId as $id) {
                $info = query(self::table, " id = '$id'");
                $salary = query('salary',"month = '$info[month]'");
                $staff = query('staff', " stid = '$info[stid]'");
                if($salary['state'] !='已通过'){
                    $this->logText(["type" => self::page, "text" =>str_replace(['{{staffName}}','{{name}}','{{month}}'],[$this->control['name'],$staff['name'],$info['month']],L('salary.table.pay_warn_one'))]);
                }elseif (!$info['isConfirm']) {
                    $this->logText(["type" => self::page, "text" =>str_replace(['{{staffName}}','{{name}}','{{month}}'],[$this->control['name'],$staff['name'],$info['month']],L('salary.table.pay_warn_two'))]);
                } elseif (!$info['isPay']) {
                    //找当月的奖惩金额
                    $rewards = find(['table'=>'rewards','where'=>"staffId = '$staff[stid]' and date_format(recordDate,'%Y-%m') ='$info[month]' and state = '已通过'",'sum'=>"money"]);
                    //社保扣款(找缴款月份为这个月的)
                    $insure = query('insure', " stid = '$staff[stid]' and payMoon = '$info[month]'");
                    $insure['personal']=$insure['personal']?:0;
                    //公积金扣款
                    $providentFund = query('provident_fund', " staffId = '$staff[stid]' and month = '$info[month]' and isCommit = 1");
                    $providentFund['decMoney'] = $providentFund['decMoney']?:0;
                    //个税扣款
                    $personalTax = query('personal_tax', " staffId = '$staff[stid]' and month = '$info[month]' and isCommit = 1");
                    $personalTax['decMoney']=$personalTax['decMoney']?:0;
                    $yanglao = find(array('table' => 'insure', 'single' => "moon = '$info[month]' and subject = '养老保险'  and stid ='$info[stid]'", 'field' => "ifnull(sum(personal),0) as money"));
                    $yiliao = find(array('table' => 'insure', 'single' => "moon = '$info[month]' and subject = '基本医疗'  and stid ='$info[stid]'", 'field' => "ifnull(sum(personal),0) as money"));
                    $shiye = find(array('table' => 'insure', 'single' => "moon = '$info[month]' and subject = '失业保险'  and stid ='$info[stid]'", 'field' => "ifnull(sum(personal),0) as money"));
                    $text = $insure['text'] ? $insure['text'] . '，' : '';
                    $text .= $providentFund['text'] ? $providentFund['text'] . '，' : '';
                    $text .= $personalTax['text'] ? $personalTax['text'] . '，' : '';
                    $text .= $info['text'] ? $info['text'] . '，' : '';
                    $warn = update(array(
                        "table" => self::table,
                        "field" => [
                            'agedFee'=>$yanglao['money'],
                            'medicalFee'=>$yiliao['money'],
                            'unemploymentFee'=>$shiye['money'],
                            'insure' => $insure['personal'],
                            'providentFund' => $providentFund['decMoney'],
                            'personalTax' => $personalTax['decMoney'],
                            'rewards'=>$rewards,
                            'payMoney' => $info['money']+$rewards - $insure['personal']-$providentFund['decMoney']-$personalTax['decMoney'],
                            'isPay' => 1,
                            'text'=>$text,
                        ],
                        'where' => " id = '$id'"
                    ));
                    if ($warn == '更新成功') {
                        $this->insetProfit($id);
                        $x++;
                        //添加日志
                        $text = str_replace(['{{staffName}}','{{name}}','{{month}}','{{id}}'],[$this->control['name'],$staff['name'],$info['month'],$id],L('salary.table.payText'));
                        $this->logText(["type" => self::page, "text" => $text]);
                    }
                }
            }
            //返回
            $_SESSION['warn'] =str_replace(['{{x}}'],[$x],L('salary.table.payData'));
            $json['warn'] = 2;
            $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home&id=all";
        }
        //返回
        return json_encode($json, 320);
    }

    //写入到收支平衡表中
    public function insetProfit($id)
    {
        $info = query(self::table, " id = '$id'");
        insert(array(
            'table' => 'profit',
            'field' => [
                'id' => self::getId(),
                'stid' => $info['stid'],
                'target' => L('salary.table.gong_zi_bo_fu'),
                'targetId' => $info['id'],
                'direction' => L('salary.table.zhi_chu'),
                'type' => L('salary.table.gong_zi_bo_fu'),
                'money' => $info['payMoney'],
                'payDate' => $this->date,
                'updateTime' => $this->time,
                'time' => $this->time
            ]
        ));
    }

    // 操作中转
    public function operate()
    {
        $act = $this->post('act') ?? '';
        $pwd = false; // 需要密码
        switch ($act) {
            default:
                $act = 'del';
                $msg = L('salary.table.delPaySlip');
                $title = self::page. 'Delete';
                $function = 'delete';
                $form = self::page . 'OperateForm, listForm';
                $power = '';
                break;
        }
        if (!$this->power(self::page, $act)) {
            $_SESSION['warn'] = str_replace(['{{msg}}'], [$msg], L('jon.other.permission_warn'));
            $json = [
                'warn' => 2,
                'href' => root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=home',
            ];
        } else {
            return $this->confirm([
                'title' => $title,
                'function' => $function,
                'form' => $form,
                'power' => $power,
                'pwd' => $pwd,
            ]);
        }

        resp:
        return json_encode($json, 320);
    }

    /**
     * 删除
     * @return bool|string
     */
    public function delete()
    {
        $array = $this->post('listId') ?? $this->post('id');
        if (!$this->power(self::page, "del")) {
            $json['warn'] = L('salary.table.nmzscdzx');
        } elseif (empty($array)) {
            $json['warn'] = L('salary.table.nygsjdmzxzn');
        } else {
            $text = "";
            $x = 0;
            $array = is_array($array) ? $array : [$array];
            foreach ($array as $id) {
                $info = query('salary', " id = '$id' ");
                //最后删除基本参数
                delete(array("table" => 'salary', "where" => " id = '$id' "));
                //返回
                $warn = L('salary.table.sccg');
                $x++;
                $text .= str_replace(['{{month}}','{{id}}'],[$info['month'],$info['id']],L('salary.table.pay_del_text')). $warn . "。<br>";
            }
            //添加日志
            $text = str_replace(['{{staffName}}'],[$this->control['name']],L('salary.table.pay_del_log')). "<br>" . $text;
            $this->logText(array("type" => self::page, "text" => $text));
            $_SESSION['warn'] = str_replace(['{{x}}'],[$x],L('salary.table.pay_del_warn'));
            $json['warn'] = 2;
            $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home";
        }
        return json_encode($json, 320);
    }

    /**
     * 打印
     */
    public function printPage(): string
    {

        $salary = query('salary', " id = '{$this->get('id')}'");
        $all = find(array('table'=>'work_sign_record','where'=>"month = '$salary[month]' order by updateTime asc "));
        $companyName = para('companyName');//公司名称
        $goodsHtml = '';
        $name = L('staffProfiles.table.name');
        $month = L('performance.table.month');
        $sjcqts = L('salary.table.sjcqts');
        $structureDetails = L('salary.table.structureDetails');
        $socialFundDetail = L('salary.table.socialFundDetail');
        $incomeText = L('salary.table.income');
        $shi_fa = L('salary.table.shi_fa');
        $bei_zhu = L('salary.table.bei_zhu');
        $ji_ben_gong_zi = L('salary.table.ji_ben_gong_zi');
        $gwgz = L('salary.table.gwgz');
        $tong_xun_bu_tie = L('salary.table.tong_xun_bu_tie');
        $jtbt = L('salary.table.jtbt');
        $ji_xiao_gong_zi = L('salary.table.ji_xiao_gong_zi');
        $ji_jian_gong_zi = L('salary.table.ji_jian_gong_zi');
        $ji_shi_gong_zi = L('salary.table.ji_shi_gong_zi');
        $glgz = L('salary.table.glgz');
        $xue_li_jin_tie = L('salary.table.xue_li_jin_tie');
        $zcjt = L('salary.table.zcjt');
        $gao_wen_bu_tie = L('salary.table.gao_wen_bu_tie');
        $jia_ban_bu_tie = L('salary.table.jia_ban_bu_tie');
        $qi_ta_bu_tie = L('salary.table.qi_ta_bu_tie');
        $bsjkk = L('salary.table.bsjkk');
        $chi_dao_zao_tui = L('salary.table.chi_dao_zao_tui');
        $qi_ta_kou_kuan = L('salary.table.qi_ta_kou_kuan');
        $zxfy = L('salary.table.zxfy');
        $jcfy = L('salary.table.jcfy');
        $ying_fa_gong_zi = L('salary.table.ying_fa_gong_zi');
        $quan_qin_jiang = L('salary.table.quan_qin_jiang');
        $ylbx = L('salary.table.ylbx');
        $medical_insurancei = L('salary.table.medical_insurance');
        $shi_ye_bao_xian = L('salary.table.shi_ye_bao_xian');
        $she_bao_xiao_ji = L('salary.table.she_bao_xiao_ji');
        $gong_ji_jin = L('salary.table.gong_ji_jin');
        $dkgrzds = L('salary.table.dkgrzds');
        $shyd = L('salary.table.shyd');
        $sign = L('salary.table.sign');
        foreach ($all['array'] as $index => $array) {
            $days = find(array('table'=>'work_sign','field'=>"count(distinct(date_format(signTime,'%Y-%m-%d'))) as day","single"=>"stid = '$array[stid]' and date_format(signTime,'%Y-%m') = '$array[month]'"))['day'];
            //找当月的奖惩金额
            $rewards = find(['table'=>'rewards','where'=>"staffId = '$array[stid]' and date_format(recordDate,'%Y-%m') ='$array[month]' and state = '已通过'",'sum'=>"money"]);
            $array['money']+=$rewards;
            $income = $array['money']-$array['insure']-$array['providentFund'];
            $incomeAfterTax = $income-$array['personalTax'];
            $goodsHtml .= <<<eof
<table class='printTable'  data-op-type='block-box'>
                <tbody class='nop-fill-box'>
                <tr class="have_border">
                    <td rowspan="2" style="vertical-align:middle">$name</td>
                    <td rowspan="2" style="vertical-align:middle">$month</td>
                    <td rowspan="2" style="vertical-align:middle">$sjcqts</td>
                    <td colspan="14" class="center">$structureDetails</td>
                </tr>
                <tr class="have_border">
                    <td>$ji_ben_gong_zi</td><td>$gwgz</td>
                    <td>$tong_xun_bu_tie</td><td>$jtbt</td>
                    <td>$ji_xiao_gong_zi</td><td>$ji_jian_gong_zi</td><td>$ji_shi_gong_zi</td><td>$glgz</td>
                    <td>$xue_li_jin_tie</td><td>$zcjt</td>
                    <td>$gao_wen_bu_tie</td><td>$jia_ban_bu_tie</td>
                    <td>$qi_ta_bu_tie</td><td>$quan_qin_jiang</td>
                </tr>
                <tr class="have_border">
                      <td rowspan="4">{$array['name']}</td>
                     <td rowspan="4">{$array['month']}</td>
                     <td>{$days}</td>
                     <td>{$array['baseMoney']}</td>
                     <td>{$array['jobMoney']}</td>
                     <td>{$array['telFee']}</td>
                     <td>{$array['trafficFee']}</td>
                     <td>{$array['performance']}</td>
                     <td>{$array['pieceSalary']}</td>
                     <td>{$array['hourMoney']}</td>
                     <td>{$array['workAgeFee']}</td>
                     <td>{$array['educationFee']}</td>
                     <td>{$array['jobTitleFee']}</td>
                     <td>{$array['temperatureFee']}</td>
                     <td>{$array['overtimeFee']}</td>
                     <td>{$array['otherFee']}</td>
                     <td>{$array['fullAttendance']}</td>
                   
                 </tr>
                <tr class="have_border">
                 <td colspan="6" class="center">$structureDetails</td>
                 <td colspan="5" class="center">$socialFundDetail</td>
                    <td rowspan="2" style="vertical-align:middle" class="center">$incomeText</td>
                    <td colspan="2" class="center">$shi_fa</td>
                    <td style="vertical-align:middle" class="center" colspan="3">$sign</td>
                </tr>
                <tr class="have_border">
                    <td>$bsjkk</td>
                    <td>$chi_dao_zao_tui</td>
                    <td>$qi_ta_kou_kuan</td>
                    <td>$zxfy</td>
                    <td>$jcfy</td>
                    <td>$ying_fa_gong_zi</td>                
                    <td>$ylbx</td>
                    <td>$medical_insurancei</td><td>$shi_ye_bao_xian</td>
                    <td>$she_bao_xiao_ji</td><td>$gong_ji_jin</td><td>$dkgrzds</td>
                    <td>$shyd</td>
                     <td rowspan="2" colspan="3"></td>
                </tr>
                 <tr class="have_border">
                   <td>{$array['leaveMoney']}</td>
                     <td>{$array['lateMoney']}</td>
                     <td>{$array['otherDecMoney']}</td>
                      <td>{$array['liveFee']}</td>
                       <td>{$rewards}</td>
                     <td>{$array['money']}</td>
                     <td>{$array['agedFee']}</td>
                     <td>{$array['medicalFee']}</td>
                     <td>{$array['unemploymentFee']}</td>
                     <td>{$array['insure']}</td>
                     <td>{$array['providentFund']}</td>
                     <td class="center">$income</td>
                     <td>{$array['personalTax']}</td>
                     <td>$incomeAfterTax</td>
                 </tr>
               </tbody>
              </table>
eof;
        }
        $html = <<<eof
                    <div id="content-box" style="display: none">
                        <div data-op-type='new-page'></div>
                    <!--    <div data-op-type="pendants">&lt;!&ndash; 定义页面部件（页眉/页脚/书签/水印背景等） &ndash;&gt;-->
                    <!--        <div class='pendant-title'>实发工资表</div>-->
                    <!--    </div>-->
                       <div>
                              <div class='printTitle' style='font-weight: bold'>{$companyName}工资表</div>
                              <div class='printSubTitle'></div>
                                 {$goodsHtml}
                       </div>
                    </div>
                  <style>
                  .footer-ul-parent{float: right;margin-right: 10px}
                  .footer-ul li{margin-top: 10px}
                  .printTable{font-size: 12px;margin-top: 50px;}
                  .printTable td{
                 
                  white-space: nowrap;
                
                  }
                  .table-top-title{
                    height: 30px;
                    line-height: 30px;
                    font-size: 12px;
                    margin-top: 20px;
                  }
                  .table-top-title>ul>li{float: left;width: 250px;}
</style>
eof;
        $print = new printClass();

        return $print->showPrint($html, 'landscape',['pageSize'=>'A4']);
    }

    /**
     * 导出模板字段初始化
     * @return array[]
     */
    public function exportFieldInit($classify=''): array
    {
        return match ($classify) {
            '已拨付'=>  [
                [
                    'columnName'=>'部门',
                    'aliasName'=>'部门',
                ],
                [
                    'columnName'=>'职位',
                    'aliasName'=>'职位',
                ],
                [
                    'columnName'=>'姓名',
                    'aliasName'=>'姓名',
                ],
                [
                    'columnName'=>'身份证号',
                    'aliasName'=>'身份证号',
                ],
                [
                    'columnName'=>'手机号',
                    'aliasName'=>'手机号',
                ],
                [
                    'columnName'=>'月份',
                    'aliasName'=>'月份',
                ],
                [
                    'columnName'=>'实际出勤天数',
                    'aliasName'=>'实际出勤天数',
                ],
                [
                    'columnName'=>'应出勤天数',
                    'aliasName'=>'应出勤天数',
                ],
                [
                    'columnName'=>'基本工资',
                    'aliasName'=>'基本工资',
                ],
                [
                    'columnName'=>'岗位工资',
                    'aliasName'=>'岗位工资',
                ],
                [
                    'columnName'=>'通讯补贴',
                    'aliasName'=>'通讯补贴',
                ],
                [
                    'columnName'=>'交通补贴',
                    'aliasName'=>'交通补贴',
                ],
                [
                    'columnName'=>'绩效工资',
                    'aliasName'=>'绩效工资',
                ],
                [
                    'columnName'=>'计件工资',
                    'aliasName'=>'计件工资',
                ],
                [
                    'columnName'=>'计时工资',
                    'aliasName'=>'计时工资',
                ],
                [
                    'columnName'=>'工龄工资',
                    'aliasName'=>'工龄工资',
                ],
                [
                    'columnName'=>'学历津贴',
                    'aliasName'=>'学历津贴',
                ],
                [
                    'columnName'=>'职称津贴',
                    'aliasName'=>'职称津贴',
                ],
                [
                    'columnName'=>'高温补贴',
                    'aliasName'=>'高温补贴',
                ],
                [
                    'columnName'=>'加班补贴',
                    'aliasName'=>'加班补贴',
                ],
                [
                    'columnName'=>'其他补贴',
                    'aliasName'=>'其他补贴',
                ],
                [
                    'columnName'=>'全勤奖',
                    'aliasName'=>'全勤奖',
                ],
                [
                    'columnName'=>'病事假扣款',
                    'aliasName'=>'病事假扣款',
                ],
                [
                    'columnName'=>'迟到早退',
                    'aliasName'=>'迟到早退',
                ],
                [
                    'columnName'=>'其他扣款',
                    'aliasName'=>'其他扣款',
                ],
                [
                    'columnName'=>'住宿费用',
                    'aliasName'=>'住宿费用',
                ],
                [
                    'columnName'=>'奖惩金额',
                    'aliasName'=>'奖惩金额',
                ],
                [
                    'columnName'=>'应发工资',
                    'aliasName'=>'应发工资',
                ],
                [
                    'columnName'=>'养老保险',
                    'aliasName'=>'养老保险',
                ],
                [
                    'columnName'=>'医疗保险',
                    'aliasName'=>'医疗保险',
                ],
                [
                    'columnName'=>'失业保险',
                    'aliasName'=>'失业保险',
                ],
                [
                    'columnName'=>'社保小计',
                    'aliasName'=>'社保小计',
                ],
                [
                    'columnName'=>'公积金',
                    'aliasName'=>'公积金',
                ],
                [
                    'columnName'=>'代扣个人所得税',
                    'aliasName'=>'代扣个人所得税',
                ],
                [
                    'columnName'=>'税后应得',
                    'aliasName'=>'税后应得',
                ],
                [
                    'columnName'=>'实发',
                    'aliasName'=>'实发',
                ],
                [
                    'columnName'=>'备注',
                    'aliasName'=>'备注',
                ],

            ],
            default=>  [
                [
                    'columnName'=>'部门',
                    'aliasName'=>'部门',
                ],
                [
                    'columnName'=>'职位',
                    'aliasName'=>'职位',
                ],
                [
                    'columnName'=>'姓名',
                    'aliasName'=>'姓名',
                ],
                [
                    'columnName'=>'身份证号',
                    'aliasName'=>'身份证号',
                ],
                [
                    'columnName'=>'手机号',
                    'aliasName'=>'手机号',
                ],
                [
                    'columnName'=>'月份',
                    'aliasName'=>'月份',
                ],
                [
                    'columnName'=>'实际出勤天数',
                    'aliasName'=>'实际出勤天数',
                ],
                [
                    'columnName'=>'应出勤天数',
                    'aliasName'=>'应出勤天数',
                ],
                [
                    'columnName'=>'基本工资',
                    'aliasName'=>'基本工资',
                ],
                [
                    'columnName'=>'岗位工资',
                    'aliasName'=>'岗位工资',
                ],
                [
                    'columnName'=>'通讯补贴',
                    'aliasName'=>'通讯补贴',
                ],
                [
                    'columnName'=>'交通补贴',
                    'aliasName'=>'交通补贴',
                ],
                [
                    'columnName'=>'绩效工资',
                    'aliasName'=>'绩效工资',
                ],
                [
                    'columnName'=>'计件工资',
                    'aliasName'=>'计件工资',
                ],
                [
                    'columnName'=>'计时工资',
                    'aliasName'=>'计时工资',
                ],
                [
                    'columnName'=>'工龄工资',
                    'aliasName'=>'工龄工资',
                ],
                [
                    'columnName'=>'学历津贴',
                    'aliasName'=>'学历津贴',
                ],
                [
                    'columnName'=>'职称津贴',
                    'aliasName'=>'职称津贴',
                ],
                [
                    'columnName'=>'高温补贴',
                    'aliasName'=>'高温补贴',
                ],
                [
                    'columnName'=>'加班补贴',
                    'aliasName'=>'加班补贴',
                ],
                [
                    'columnName'=>'其他补贴',
                    'aliasName'=>'其他补贴',
                ],
                [
                    'columnName'=>'全勤奖',
                    'aliasName'=>'全勤奖',
                ],
                [
                    'columnName'=>'病事假扣款',
                    'aliasName'=>'病事假扣款',
                ],
                [
                    'columnName'=>'迟到早退',
                    'aliasName'=>'迟到早退',
                ],
                [
                    'columnName'=>'其他扣款',
                    'aliasName'=>'其他扣款',
                ],
                [
                    'columnName'=>'住宿费用',
                    'aliasName'=>'住宿费用',
                ],
                [
                    'columnName'=>'奖惩金额',
                    'aliasName'=>'奖惩金额',
                ],
                [
                    'columnName'=>'应发工资',
                    'aliasName'=>'应发工资',
                ],
                [
                    'columnName'=>'养老保险',
                    'aliasName'=>'养老保险',
                ],
                [
                    'columnName'=>'医疗保险',
                    'aliasName'=>'医疗保险',
                ],
                [
                    'columnName'=>'失业保险',
                    'aliasName'=>'失业保险',
                ],
                [
                    'columnName'=>'社保小计',
                    'aliasName'=>'社保小计',
                ],
                [
                    'columnName'=>'公积金',
                    'aliasName'=>'公积金',
                ],
                [
                    'columnName'=>'代扣个人所得税',
                    'aliasName'=>'代扣个人所得税',
                ],
                [
                    'columnName'=>'税后应得',
                    'aliasName'=>'税后应得',
                ],
                [
                    'columnName'=>'备注',
                    'aliasName'=>'备注',
                ],

            ]
        };
    }
}
